package golib

import (
	"time"

	"github.com/go-redis/redis"
)

const mqkey string = "mq:delay_queue"

type RedisZ redis.Z

var RedisClient *redis.Client

// DelayQueue 延迟队列 (exectime:0=立马执行;时间戳=指定时间戳执行;1=延迟到第二天01点再执行)
func DelayQueue_del(call string, data Map, exectime float64) {
	member := Map{
		"call":       call,
		"data":       data,
		"createtime": time.Now(),
	}
	if exectime == 1 {
		t := time.Now().AddDate(0, 0, 1).Format("2006-01-02") + " 01:" + time.Now().Format("04:05")
		loc, _ := time.LoadLocation("Local")
		t1, _ := time.ParseInLocation("2006-01-02 15:04:05", t, loc)
		exectime = float64(t1.Unix())
		Log(t, exectime)
	}
	Redis().ZAdd(mqkey, redis.Z{Score: exectime, Member: ObjToJson(member)})
}

// Redis 连接redis.
func Redis() *redis.Client {
	if RedisClient != nil {
		return RedisClient
	}
	conf := Conf("redis")
	poolSize := int(Int64(conf["poolSize"]))
	if poolSize > 0 {
		Log("redis pool size:", poolSize)
	} else {
		poolSize = int(1000)
	}
	RedisClient = redis.NewClient(&redis.Options{
		Addr:     conf["address"],
		Password: conf["password"],
		DB:       int(Int64(conf["db"])),
		PoolSize: poolSize,
	})
	pong, err := RedisClient.Ping().Result()
	if err != nil {
		Log("redis连接错误:", err, pong)
	}
	return RedisClient
}
